﻿@model dynamic

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
    ViewData["Title"] = "角色管理";
    Layout = "_Layout";
}
@Html.AntiForgeryToken()
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>角色管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<script src="~/layui/layui.js"></script>
	<link href="~/layui/css/layui.css" rel="stylesheet" />
    <style>
        .layui-form-item .layui-input-inline {
            width: 180px;
        }

        .layui-card-header {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            height: 50px;
            line-height: 50px;
        }

        body {
            padding: 15px;
            background-color: #f2f2f2;
        }

        .layui-fluid {
            padding: 15px;
        }

        .layui-card {
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
    </style>
</head>
<body>
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <h2>角色管理</h2>
                    </div>
                </div>
            </div>
            <div class="layui-card-body">
                <!-- 工具栏 -->
                <div class="layui-btn-container" style="margin-bottom: 10px;">
                    <button class="layui-btn layui-btn-normal" id="btnAdd">
                        <i class="layui-icon">&#xe654;</i> 新增角色
                    </button>
                </div>
                <!-- 数据表格 -->
				<table class="layui-table" lay-filter="roleTable" id="roleTable"></table>
            </div>
        </div>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="operationTpl">
        <div class="layui-btn-group table-operation-column">
            <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="permission">
                <i class="layui-icon">&#xe672;</i> 分配权限
            </a>
            <a class="layui-btn layui-btn-xs" lay-event="edit">
                <i class="layui-icon">&#xe642;</i> 编辑
            </a>
            <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">
                <i class="layui-icon">&#xe640;</i> 删除
            </a>
        </div>
    </script>

    <!-- 添加/编辑表单弹窗 -->
    <script type="text/html" id="formTpl">
        <form class="layui-form" lay-filter="positionLevelForm" style="padding: 25px;">
            <input type="hidden" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label">角色名称</label>
                <div class="layui-input-block">
                    <div class="layui-input-inline" style="width: 280px;">
                        <input type="text" name="rolename" lay-verify="required" placeholder="请输入角色名称" autocomplete="off" class="layui-input">
                    </div>
                    <div class="layui-form-mid layui-word-aux">必填项</div>
                </div>
            </div>

            <div class="layui-form-item" style="text-align: center; margin-top: 30px;">
                <button type="button" class="layui-btn" lay-submit lay-filter="submitForm">
                    <i class="layui-icon layui-icon-ok"></i> 提交
                </button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">
                    <i class="layui-icon layui-icon-close"></i> 取消
                </button>
            </div>
        </form>
    </script>

    <!-- 权限分配弹窗模板 -->
    <script type="text/html" id="permissionTpl">
        <div class="permission-dialog-content">
            <!-- 搜索框 -->
            <div class="layui-form permission-search">
                <div class="layui-input-group">
                    <input type="text" id="permissionSearchInput" placeholder="搜索权限" class="layui-input">
                    <div class="layui-input-suffix">
                        <button type="button" id="permissionSearchBtn" class="layui-btn layui-btn-primary">
                            <i class="layui-icon">&#xe615;</i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- 权限树 -->
            <div id="permissionTree"></div>

            <!-- 底部按钮 -->
            <div style="text-align: center; margin-top: 25px;">
                <button type="button" class="layui-btn" id="savePermissionBtn">
                    <i class="layui-icon layui-icon-ok"></i> 保存
                </button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelPermissionBtn">
                    <i class="layui-icon layui-icon-close"></i> 取消
                </button>
            </div>
        </div>
    </script>
    
    <script>
        layui.use(['table', 'form', 'layer', 'tree'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.jquery;

            // 初始化表格
            var tableIns = table.render({
                elem: '#roleTable',
                url: '/RBAC/QueryRole',
                method: "get",
                page: true,
                limits: [10, 20, 50, 100],
                limit: 10,
                cols: [[
                    { type: 'checkbox', width: 50 },
                    { field: 'id', title: 'ID', width: 80, sort: true },
                    { field: 'rolename', title: '角色名称', width: 200 },
                    { title: '操作', width: 250, toolbar: '#operationTpl', fixed: 'right' }
                ]],
                response: {
                    statusCode: 0
                },
                parseData: function (res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                },
                skin: 'line', // 表格风格
                even: true, // 开启隔行背景
                size: 'lg', // 大尺寸
                text: {
                    none: '暂无相关数据' // 空数据提示
                }
            });

            // 表格搜索
            form.on('submit(searchBtn)', function (data) {
                tableIns.reload({
                    where: data.field,
                    page: {
                        curr: 1
                    }
                });
                return false;
            });

            // 重置按钮
            $('#resetBtn').on('click', function () {
                // 重置表单
                document.querySelector('form[lay-filter="searchForm"]').reset();
                // 重新加载表格
                tableIns.reload({
                    where: {},
                    page: {
                        curr: 1
                    }
                });
            });

            // 刷新表格
            $('#refreshTableBtn').on('click', function () {
                tableIns.reload();
            });

            // 监听表格工具栏事件
            table.on('tool(roleTable)', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;

                if (layEvent === 'edit') {
                    // 编辑角色
                    openEditDialog(data);
                } else if (layEvent === 'delete') {
                    // 删除角色
                    layer.confirm('确定要删除该角色吗？', function (index) {
                        $.ajax({
                            url: '/rbac/delrole',
                            type: 'POST',
                            data: {
                                id: data.id,
                                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                            },
                            success: function (res) {
                                if (res.success) {
                                    layer.msg('删除成功');
                                    // 重新加载表格
                                    tableIns.reload();
                                } else {
                                    layer.msg('删除失败：' + res.message);
                                }
                            },
                            error: function () {
                                layer.msg('删除请求失败，请稍后再试');
                            }
                        });
                        layer.close(index);
                    });
                } else if (layEvent === 'permission') {
                    // 分配权限
                    openPermissionDialog(data.id);
                }
            });

            // 添加角色按钮点击事件
            $('#btnAdd').on('click', function () {
                openEditDialog();
            });

            // 打开编辑弹窗
            function openEditDialog(data) {
                // 弹窗标题
                var title = data ? '编辑角色' : '添加角色';

                layer.open({
                    type: 1,
                    title: title,
                    content: $('#formTpl').html(),
                    area: ['500px', '280px'],
                    success: function (layero, index) {
                        form.render();

                        // 取消按钮
                        $('#cancelBtn').on('click', function () {
                            layer.close(index);
                        });

                        // 如果是编辑，回填数据
                        if (data) {
                            form.val('positionLevelForm', {
                                'id': data.id,
                                'rolename': data.rolename
                            });
                        }

                        // 表单提交
                        form.on('submit(submitForm)', function (formData) {
                            var url = data ? '/rbac/uprole' : '/rbac/addrole';
                            var field = formData.field;

                            // 添加防伪标记
                            field.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();

                            $.ajax({
                                url: url,
                                type: 'POST',
                                data: field,
                                success: function (res) {
                                    if (res.success) {
                                        layer.msg('保存成功');
                                        layer.close(index);
                                        // 重新加载表格
                                        tableIns.reload();
                                    } else {
                                        layer.msg('保存失败：' + res.message);
                                    }
                                },
                                error: function () {
                                    layer.msg('保存失败');
                                }
                            });
                            return false;
                        });
                    }
                });
            }

            // 打开权限分配弹窗
            function openPermissionDialog(roleId) {
                layer.open({
                    type: 1,
                    title: '分配权限',
                    content: $('#permissionTpl').html(),
                    area: ['500px', '500px'],
                    success: function (layero, index) {
                        // 加载权限树
                        loadPermissionTree(roleId, layero);

                        // 取消按钮
                        $('#cancelPermissionBtn').on('click', function () {
                            layer.close(index);
                        });

                        // 保存按钮
                        $('#savePermissionBtn').on('click', function () {
                            saveRolePermissions(roleId, index);
                        });

                        // 权限搜索
                        $('#permissionSearchBtn').on('click', function () {
                            var keyword = $('#permissionSearchInput').val().toLowerCase();
                            if (!keyword) {
                                return;
                            }

                            // 查找包含关键字的节点并高亮显示
                            $('#permissionTree .layui-tree-txt').each(function () {
                                var text = $(this).text().toLowerCase();
                                if (text.indexOf(keyword) !== -1) {
                                    $(this).css('color', '#FF5722');
                                    // 展开父节点
                                    $(this).parents('.layui-tree-pack').each(function () {
                                        $(this).prev('.layui-tree-spread').click();
                                    });
                                } else {
                                    $(this).css('color', '');
                                }
                            });
                        });
                    }
                });
            }

            // 加载权限树
            function loadPermissionTree(roleId, layero) {
                // 显示加载中效果
                var loadingIndex = layer.msg('正在加载权限数据...', {
                    icon: 16,
                    shade: 0.01,
                    time: 0
                });

                // 获取所有权限
                $.ajax({
                    url: '/rbac/GetAllPermissions',
                    type: 'GET',
                    success: function(res) {
                        layer.close(loadingIndex);

                        if (res.success) {
                            var permissions = res.data;
                            console.log('获取到的权限数据:', permissions);

                            // 如果权限列表为空，显示提示信息
                            if (!permissions || permissions.length === 0) {
                                $('#permissionTree').html('<div class="layui-none">暂无权限数据，请先添加权限</div>');
                                return;
                            }

                            // 获取角色已有权限
                            $.ajax({
                                url: '/rbac/GetRolePermissions',
                                type: 'GET',
                                data: { roleId: roleId },
                                success: function(roleRes) {
                                    if (roleRes.success) {
                                        var rolePermissions = roleRes.data;
                                        console.log('角色已有权限:', rolePermissions);

                                        // 构建权限树数据
                                        var treeData = buildPermissionTree(permissions, rolePermissions);
                                        console.log('构建的权限树数据:', treeData);

                                        // 渲染权限树
                                        layui.tree.render({
                                            elem: '#permissionTree',
                                            data: treeData,
                                            showCheckbox: true,
                                            id: 'permissionTreeId',
                                            onlyIconControl: false, // 点击节点名称也可以展开
                                            accordion: false, // 不使用手风琴模式
                                            isJump: false, // 不允许跳转
                                            click: function(obj) {
                                                // 点击节点名称时也触发复选框切换
                                                var $checkbox = $(obj.elem).find('.layui-form-checkbox');
                                                $checkbox.trigger('click');
                                            }
                                        });
                                    } else {
                                        layer.msg('获取角色权限失败: ' + roleRes.message, {icon: 2});
                                    }
                                },
                                error: function(xhr) {
                                    layer.msg('服务器错误', {icon: 2});
                                }
                            });
                        } else {
                            layer.msg('获取权限列表失败: ' + res.message, {icon: 2});
                        }
                    },
                    error: function(xhr) {
                        layer.close(loadingIndex);
                        layer.msg('服务器错误', {icon: 2});
                    }
                });
            }

            // 构建权限树
            function buildPermissionTree(permissions, rolePermissions) {
                // 由于Permissions实体中没有parentId字段，我们将所有权限作为顶级节点
                var treeData = [];

                permissions.forEach(function(permission) {
                    var node = {
                        id: permission.id,
                        title: permission.permissionName || '未命名权限',
                        checked: rolePermissions.indexOf(permission.id) !== -1
                    };

                    treeData.push(node);
                });

                return treeData;
            }

            // 保存角色权限
            function saveRolePermissions(roleId, index) {
                // 获取选中的权限
                var checkedData = layui.tree.getChecked('permissionTreeId');
                var permissionIds = [];

                // 递归获取所有选中的节点ID
                function getCheckedNodesInfo(nodes) {
                    nodes.forEach(function(node) {
                        permissionIds.push(node.id);
                        if (node.children && node.children.length > 0) {
                            getCheckedNodesInfo(node.children);
                        }
                    });
                }

                getCheckedNodesInfo(checkedData);

                // 显示加载中效果
                var loadingIndex = layer.load(2);

                // 保存权限
                $.ajax({
                    url: '/rbac/SaveRolePermissions',
                    type: 'POST',
                    data: {
                        roleId: roleId,
                        permissionIds: permissionIds,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    traditional: true, // 用于数组参数
                    success: function(res) {
                        layer.close(loadingIndex);
                        if (res.success) {
                            layer.msg('保存成功', {icon: 1, time: 1000});
                            layer.close(index);
                            // 重新加载表格
                            tableIns.reload();
                        } else {
                            layer.msg('保存失败: ' + res.message, {icon: 2});
                        }
                    },
                    error: function(xhr) {
                        layer.close(loadingIndex);
                        layer.msg('服务器错误', {icon: 2});
                    }
                });
            }
        });
    </script>
</body>
</html>